<?php

App::uses('AdminAppController', 'Admin.Controller');
App::uses('AppController', 'Controller');

class BrokersController extends AdminAppController {

    var $helpers = array('Form');

    public function beforeFilter() {
        $this->Auth->allow('index', 'edit', 'add', 'delete', 'opinions', 'add_opinion', 'delete_opinion', 'edit_opinion');
    }

    function index() {
        $this->paginate = array(
            'fields' => array(
                'Broker.*', 'Company.name'
            ),
            'recursive' => -1,
            'joins' => array(
                array(
                    'table' => 'companies',
                    'type' => 'left',
                    'alias' => 'Company',
                    'conditions' => array('Broker.company = Company.id')
                )
            ),
            'limit' => 25,
            'order' => array('Broker.id' => 'desc')
        );

        // we are using the 'Admin' model
        $rows = $this->paginate('Broker');

        // pass the value to our view.ctp
        $this->set('rows', $rows);
    }

    function opinions($id) {
        if (!$id) {
            throw new NotFoundException(__('Invalid post'));
        }
        $post = $this->Broker->findById($id);
        if (!$post) {
            throw new NotFoundException(__('Invalid post'));
        }
        $this->set('broker', $post);
        $this->loadModel('Opinion');

        $this->paginate = array(
            'fields' => array(
                'Opinion.*', 'Stock.name'
            ),
            'recursive' => -1,
            'joins' => array(
                array(
                    'table' => 'stocks',
                    'type' => 'left',
                    'alias' => 'Stock',
                    'conditions' => array('Opinion.stock = Stock.id')
                )
            ),
            'limit' => 25,
            'order' => array('Opinion.id' => 'desc'),
            'conditions' => array('Opinion.broker' => $id)
        );

        // we are using the 'Admin' model
        $rows = $this->paginate('Opinion');

        // pass the value to our view.ctp
        $this->set('rows', $rows);
    }

    function edit($id = null) {
        if (!$id) {
            throw new NotFoundException(__('Invalid post'));
        }
        $post = $this->Broker->findById($id);
        if (!$post) {
            throw new NotFoundException(__('Invalid post'));
        }

        $this->loadModel('Company');
        $companies = $this->Company->find('all');
        $this->set('companies', $companies);

        if ($this->request->is(array('post', 'put'))) {
            $this->Broker->id = $id;

            $old_company = $post['Broker']['company'];

            if ($this->Broker->save($this->request->data)) {
                //update old company
                $total_old = $this->Broker->find('count', array('conditions' => array('status' => 1, 'company' => $old_company)));
                $old_data = array('id' => $old_company, 'brokers' => $total_old);
                $this->Company->save($old_data);

                //update new company
                $total_new = $this->Broker->find('count', array('conditions' => array('status' => 1, 'company' => $this->request->data['company'])));
                $new_data = array('id' => $this->request->data['company'], 'brokers' => $total_new);
                $this->Company->save($new_data);

                $this->Session->setFlash('Broker has been updated.!', 'default', array(), 'good');
                return $this->redirect(array('action' => 'index'));
            }
            $this->Session->setFlash('Unable to update broker.!', 'default', array(), 'bad');
        }

        if (!$this->request->data) {
            $this->request->data = $post;
        }
    }

    function add() {
        $this->loadModel('Company');

        $companies = $this->Company->find('all');
        $this->set('companies', $companies);
        if ($this->request->is(array('post', 'put'))) {
            $this->request->data['date_added'] = date("Y-m-d H:i:s");

            if ($this->Broker->save($this->request->data)) {
                //update new company
                $total_new = $this->Broker->find('count', array('conditions' => array('status' => 1, 'company' => $this->request->data['company'])));
                $new_data = array('id' => $this->request->data['company'], 'brokers' => $total_new);
                $this->Company->save($new_data);

                $this->Session->setFlash('Broker has been created.!', 'default', array(), 'good');
                return $this->redirect(array('action' => 'index'));
            }
            $this->Session->setFlash('Unable to create broker.!', 'default', array(), 'bad');
        }
    }

    function delete($id = null) {
        if (!$id) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is('get')) {
            throw new MethodNotAllowedException();
        }

        $post = $this->Broker->findById($id);
        if (!$post) {
            throw new NotFoundException(__('Invalid post'));
        }


        $this->loadModel('Company');
        if ($this->Broker->delete($id)) {
            //update old company
            $total_old = $this->Broker->find('count', array('conditions' => array('status' => 1, 'company' => $post['Broker']['company'])));
            $old_data = array('id' => $post['Broker']['company'], 'brokers' => $total_old);
            $this->Company->save($old_data);

            $this->Session->setFlash('Delete success!', 'default', array(), 'good');
        } else {
            $this->Session->setFlash('Delete unsuccess!', 'default', array(), 'bad');
        }
        $this->Redirect(array('action' => 'index'));
    }

    function add_opinion($broker) {
        $this->loadModel('Stock');
        $this->loadModel('Opinion');

        if (!$broker) {
            throw new NotFoundException(__('Invalid user'));
        }

        $post = $this->Broker->findById($broker);
        if (!$post) {
            throw new NotFoundException(__('Invalid post'));
        }

        $list_stocks = $total_new = $this->Stock->find('all', array('conditions' => array('status' => 1, 'broker' => $broker)));

        if ($this->request->is(array('post', 'put'))) {

            $today = date("Y-m-d");
            $opinion_date = $this->request->data['date'];

            $today_dt = new DateTime($today);
            $expire_dt = new DateTime($opinion_date);

            if ($expire_dt > $today_dt) { /* Do something */
                $this->request->data['broker'] = $broker;

                $check = $this->Opinion->find('first', array('conditions' => array('broker' => $broker, 'stock' => $this->request->data['stock'], 'and' => array('date >=' => $this->request->data['date'] . ' 00:00:00', 'date <=' => $this->request->data['date'] . ' 23:59:59'))));

                if ($check) {
                    //update
                    $this->Opinion->id = $check['Opinion']['id'];
                    if ($this->Opinion->save($this->request->data)) {
                        $this->Session->setFlash('Opinion has been created.!', 'default', array(), 'good');
                        return $this->redirect(array('action' => 'opinions', $broker));
                    } else
                        $this->Session->setFlash('Unable to create opinion.!', 'default', array(), 'bad');
                } else {
                    //create
                    $this->Opinion->create();
                    if ($this->Opinion->save($this->request->data)) {
                        $this->Session->setFlash('Opinion has been created.!', 'default', array(), 'good');
                        return $this->redirect(array('action' => 'opinions', $broker));
                    } else
                        $this->Session->setFlash('Unable to create opinion.!', 'default', array(), 'bad');
                }
            } else {
                $this->Session->setFlash('Opinion date must greater today.', 'default', array(), 'bad');
            }
        }

        $this->set('broker', $post);
        $this->set('stocks', $list_stocks);
    }

    function delete_opinion($id = null, $broker = null) {
        $this->loadModel('Stock');
        $this->loadModel('Opinion');
        if (!$id) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is('get')) {
            throw new MethodNotAllowedException();
        }

        $post = $this->Opinion->findById($id);
        if (!$post) {
            throw new NotFoundException(__('Invalid post'));
        }


        if ($this->Opinion->delete($id)) {
            //update old company            
            $this->Session->setFlash('Delete success!', 'default', array(), 'good');
        } else {
            $this->Session->setFlash('Delete unsuccess!', 'default', array(), 'bad');
        }
        $this->Redirect(array('action' => 'opinions', $broker));
    }

    function edit_opinion($id, $broker) {
        $this->loadModel('Stock');
        $this->loadModel('Opinion');

        if (!$broker || !$id) {
            throw new NotFoundException(__('Invalid user'));
        }

        $post = $this->Broker->findById($broker);
        if (!$post) {
            throw new NotFoundException(__('Invalid post'));
        }

        $opinion = $this->Opinion->findById($id);
        if (!$opinion) {
            throw new NotFoundException(__('Invalid post'));
        }

        $list_stocks = $total_new = $this->Stock->find('all', array('conditions' => array('status' => 1, 'broker' => $broker)));

        if ($this->request->is(array('post', 'put'))) {

            $today = date("Y-m-d");
            $opinion_date = $this->request->data['date'];

            if (!$opinion['Opinion']['result']) {
                unset($this->request->data['result']);
            }

            $today_dt = new DateTime($today);
            $expire_dt = new DateTime($opinion_date);

            if ($expire_dt > $today_dt) { /* Do something */
                $this->request->data['broker'] = $broker;
                //update
                $this->Opinion->id = $id;
                if ($this->Opinion->save($this->request->data)) {
                    $this->Opinion->deleteAll(array('broker' => $broker, 'stock' => $this->request->data['stock'], 'and' => array('date >=' => $this->request->data['date'] . ' 00:00:00', 'date <=' => $this->request->data['date'] . ' 23:59:59'), 'id !=' => $id));
                    $this->Session->setFlash('Opinion has been created.!', 'default', array(), 'good');
                    return $this->redirect(array('action' => 'opinions', $broker));
                } else
                    $this->Session->setFlash('Unable to create opinion.!', 'default', array(), 'bad');
            } else {
                $this->Session->setFlash('Opinion date must greater today.', 'default', array(), 'bad');
            }
        }

        $this->set('broker', $post);
        $this->set('opinion', $opinion);
        $this->set('stocks', $list_stocks);
    }

}
